/**
 * 性能管理器 - 优化3D场景渲染性能
 * 解决光照、渲染循环、材质等性能瓶颈
 */

import * as THREE from 'three';

export class PerformanceManager {
    constructor(renderer, scene, camera) {
        this.renderer = renderer;
        this.scene = scene;
        this.camera = camera;
        
        // 性能监控
        this.stats = {
            fps: 60,
            frameTime: 16.67,
            drawCalls: 0,
            triangles: 0,
            lastFrameTime: performance.now()
        };
        
        // 性能级别
        this.performanceLevel = 'auto'; // auto, low, medium, high
        this.targetFPS = 60;
        this.minFPS = 30;
        
        // 优化设置
        this.optimizations = {
            adaptiveQuality: true,
            frustumCulling: true,
            lodEnabled: true,
            shadowOptimization: true,
            materialOptimization: true
        };
        
        // LOD管理
        this.lodLevels = new Map();
        this.lodDistance = {
            high: 10,
            medium: 25,
            low: 50
        };
        
        this.init();
    }
    
    init() {
        this.setupPerformanceMonitoring();
        this.optimizeRenderer();
        this.setupAdaptiveQuality();
        
        console.log('性能管理器已初始化');
    }
    
    /**
     * 设置性能监控
     */
    setupPerformanceMonitoring() {
        // 创建性能统计显示
        if (typeof Stats !== 'undefined') {
            this.statsDisplay = new Stats();
            this.statsDisplay.showPanel(0); // FPS
            document.body.appendChild(this.statsDisplay.dom);
            this.statsDisplay.dom.style.position = 'absolute';
            this.statsDisplay.dom.style.top = '10px';
            this.statsDisplay.dom.style.right = '10px';
            this.statsDisplay.dom.style.zIndex = '1000';
        }
        
        // 监控渲染信息
        this.monitorRenderInfo();
    }
    
    /**
     * 监控渲染信息 - 优化高/中质量切换阈值
     */
    monitorRenderInfo() {
        setInterval(() => {
            const info = this.renderer.info;
            this.stats.drawCalls = info.render.calls;
            this.stats.triangles = info.render.triangles;
            
            // 如果性能下降，自动调整质量
            // 使用更高的阈值，确保只在需要时才降低质量
            if (this.optimizations.adaptiveQuality && this.stats.fps < this.minFPS) {
                this.reduceQuality();
            } 
            // 性能足够好时提升质量，使用更合理的阈值
            else if (this.optimizations.adaptiveQuality && this.stats.fps > this.targetFPS + 5) {
                this.increaseQuality();
            }
        }, 1000);
    }
    
    /**
     * 优化渲染器设置
     */
    optimizeRenderer() {
        // 基础优化
        this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
        this.renderer.outputColorSpace = THREE.SRGBColorSpace;
        
        // 阴影优化
        this.optimizeShadows();
        
        // 启用视锥体剔除
        this.renderer.frustumCulled = true;
        
        // 优化渲染状态
        this.renderer.sortObjects = true;
        
        console.log('渲染器已优化');
    }
    
    /**
     * 优化阴影系统
     */
    optimizeShadows() {
        const performanceLevel = this.getPerformanceLevel();
        
        switch (performanceLevel) {
            case 'high':
                this.renderer.shadowMap.enabled = true;
                this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
                this.setShadowMapSize(2048);
                break;
                
            case 'medium':
                this.renderer.shadowMap.enabled = true;
                this.renderer.shadowMap.type = THREE.PCFShadowMap;
                this.setShadowMapSize(1024);
                break;
                
            case 'low':
                this.renderer.shadowMap.enabled = false;
                break;
                
            default:
                // 自动模式：根据设备性能决定
                const isHighEnd = this.detectHighEndDevice();
                if (isHighEnd) {
                    this.renderer.shadowMap.enabled = true;
                    this.renderer.shadowMap.type = THREE.PCFShadowMap;
                    this.setShadowMapSize(1024);
                } else {
                    this.renderer.shadowMap.enabled = false;
                }
        }
    }
    
    /**
     * 设置阴影贴图大小
     */
    setShadowMapSize(size) {
        this.scene.traverse((object) => {
            if (object.isDirectionalLight && object.castShadow) {
                object.shadow.mapSize.width = size;
                object.shadow.mapSize.height = size;
                object.shadow.camera.updateProjectionMatrix();
            }
        });
    }
    
    /**
     * 优化光照系统
     */
    optimizeLighting() {
        const lights = [];
        this.scene.traverse((object) => {
            if (object.isLight) {
                lights.push(object);
            }
        });
        
        // 限制阴影投射光源数量
        let shadowCasters = 0;
        const maxShadowCasters = this.getMaxShadowCasters();
        
        lights.forEach((light) => {
            if (light.isDirectionalLight || light.isSpotLight) {
                if (shadowCasters < maxShadowCasters && this.renderer.shadowMap.enabled) {
                    light.castShadow = true;
                    shadowCasters++;
                } else {
                    light.castShadow = false;
                }
                
                // 优化阴影相机范围
                if (light.shadow) {
                    this.optimizeShadowCamera(light);
                }
            }
        });
        
        console.log(`光照优化完成，${shadowCasters}个光源投射阴影`);
    }
    
    /**
     * 优化阴影相机
     */
    optimizeShadowCamera(light) {
        if (light.shadow && light.shadow.camera) {
            const camera = light.shadow.camera;
            
            if (light.isDirectionalLight) {
                // 缩小阴影相机范围以提高精度
                camera.left = -15;
                camera.right = 15;
                camera.top = 15;
                camera.bottom = -15;
                camera.near = 0.1;
                camera.far = 30;
            }
            
            camera.updateProjectionMatrix();
        }
    }
    
    /**
     * 获取最大阴影投射光源数量
     */
    getMaxShadowCasters() {
        const performanceLevel = this.getPerformanceLevel();
        
        switch (performanceLevel) {
            case 'high': return 3;
            case 'medium': return 2;
            case 'low': return 0;
            default: return this.detectHighEndDevice() ? 2 : 1;
        }
    }
    
    /**
     * 设置自适应质量
     */
    setupAdaptiveQuality() {
        this.qualityLevels = {
            low: {
                pixelRatio: 0.5,
                shadowMapSize: 512,
                enableShadows: false,
                antialias: false
            },
            medium: {
                pixelRatio: 1.0,
                shadowMapSize: 1024,
                enableShadows: true,
                antialias: true
            },
            high: {
                pixelRatio: Math.min(window.devicePixelRatio, 2),
                shadowMapSize: 2048,
                enableShadows: true,
                antialias: true
            }
        };
    }
    
    /**
     * 降低渲染质量 - 只在高与中之间切换
     */
    reduceQuality() {
        const currentLevel = this.getPerformanceLevel();
        
        if (currentLevel === 'high') {
            this.setPerformanceLevel('medium');
            console.log('性能优化：降低渲染质量到中等');
        }
    }
    
    /**
     * 提高渲染质量
     */
    increaseQuality() {
        const currentLevel = this.getPerformanceLevel();
        
        if (currentLevel === 'low') {
            this.setPerformanceLevel('medium');
        } else if (currentLevel === 'medium') {
            this.setPerformanceLevel('high');
        }
        
        console.log('性能优化：提高渲染质量到', this.performanceLevel);
    }
    
    /**
     * 设置性能级别
     */
    setPerformanceLevel(level) {
        this.performanceLevel = level;
        const settings = this.qualityLevels[level];
        
        if (settings) {
            // 应用像素比
            this.renderer.setPixelRatio(settings.pixelRatio);
            
            // 应用阴影设置
            this.renderer.shadowMap.enabled = settings.enableShadows;
            if (settings.enableShadows) {
                this.setShadowMapSize(settings.shadowMapSize);
            }
            
            // 重新优化光照
            this.optimizeLighting();
        }
    }
    
    /**
     * 获取当前性能级别
     */
    getPerformanceLevel() {
        if (this.performanceLevel === 'auto') {
            // 始终返回medium或high，不再返回low
            return this.detectHighEndDevice() ? 'high' : 'medium';
        }
        return this.performanceLevel;
    }
    
    /**
     * 检测高端设备
     */
    detectHighEndDevice() {
        // 使用现有渲染器的WebGL上下文，避免创建新的上下文
        if (this.renderer && this.renderer.getContext) {
            const gl = this.renderer.getContext();
            
            if (gl) {
                const debugInfo = gl.getExtension('WEBGL_debug_renderer_info');
                if (debugInfo) {
                    const renderer = gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL);
                    
                    // 检测高端GPU
                    const highEndGPUs = [
                        'RTX', 'GTX 1060', 'GTX 1070', 'GTX 1080', 'GTX 1660',
                        'RX 580', 'RX 590', 'RX 6600', 'RX 6700',
                        'Apple M1', 'Apple M2', 'Apple M3'
                    ];
                    
                    return highEndGPUs.some(gpu => renderer.includes(gpu));
                }
            }
        }
        
        // 备用检测：基于内存和核心数
        return navigator.hardwareConcurrency >= 8 && navigator.deviceMemory >= 8;
    }
    
    /**
     * 优化材质
     */
    optimizeMaterials() {
        this.scene.traverse((object) => {
            if (object.isMesh && object.material) {
                const materials = Array.isArray(object.material) ? object.material : [object.material];
                
                materials.forEach((material) => {
                    // 优化材质设置
                    if (material.isMeshStandardMaterial || material.isMeshPhysicalMaterial) {
                        // 降低环境贴图强度
                        material.envMapIntensity = Math.min(material.envMapIntensity || 1, 0.5);
                        
                        // 优化粗糙度和金属度
                        if (material.roughness === undefined) material.roughness = 0.8;
                        if (material.metalness === undefined) material.metalness = 0.1;
                        
                        // 禁用不必要的特性
                        material.transparent = material.transparent && material.opacity < 1;
                    }
                    
                    // 标记材质需要更新
                    material.needsUpdate = true;
                });
            }
        });
        
        console.log('材质优化完成');
    }
    
    /**
     * 设置LOD（细节层次）
     */
    setupLOD(object, distances = null) {
        if (!this.optimizations.lodEnabled) return;
        
        const lodDistances = distances || this.lodDistance;
        const lod = new THREE.LOD();
        
        // 添加不同细节层次的模型
        lod.addLevel(object, 0); // 高细节
        
        // 如果有中等细节模型，添加它
        if (object.userData.mediumLOD) {
            lod.addLevel(object.userData.mediumLOD, lodDistances.medium);
        }
        
        // 如果有低细节模型，添加它
        if (object.userData.lowLOD) {
            lod.addLevel(object.userData.lowLOD, lodDistances.low);
        }
        
        return lod;
    }
    
    /**
     * 更新性能统计
     */
    update() {
        const now = performance.now();
        const deltaTime = now - this.stats.lastFrameTime;
        
        // 计算FPS
        this.stats.fps = 1000 / deltaTime;
        this.stats.frameTime = deltaTime;
        this.stats.lastFrameTime = now;
        
        // 更新统计显示
        if (this.statsDisplay) {
            this.statsDisplay.update();
        }
        
        // 更新LOD
        if (this.optimizations.lodEnabled) {
            this.updateLOD();
        }
    }
    
    /**
     * 更新LOD
     */
    updateLOD() {
        this.scene.traverse((object) => {
            if (object.isLOD) {
                object.update(this.camera);
            }
        });
    }
    
    /**
     * 获取性能报告
     */
    getPerformanceReport() {
        return {
            fps: Math.round(this.stats.fps),
            frameTime: Math.round(this.stats.frameTime * 100) / 100,
            drawCalls: this.stats.drawCalls,
            triangles: this.stats.triangles,
            performanceLevel: this.getPerformanceLevel(),
            shadowsEnabled: this.renderer.shadowMap.enabled,
            pixelRatio: this.renderer.getPixelRatio()
        };
    }
    
    /**
     * 清理资源
     */
    dispose() {
        if (this.statsDisplay && this.statsDisplay.dom.parentNode) {
            this.statsDisplay.dom.parentNode.removeChild(this.statsDisplay.dom);
        }
        
        this.lodLevels.clear();
        
        console.log('性能管理器已清理');
    }
}